<template>
	<div class="front employeeAddForm bj">
        <el-scrollbar style="height: 100%;">
            <el-form label-width="90px" label-position="left" :model="formData" ref="formRef" status-icon :rules="formRules">
                <el-form-item label="用户名：" prop="userName" >
                    <el-input v-model.trim="formData.userName" disabled></el-input>
                </el-form-item>
                <el-form-item label="名称：" prop="name">
                    <el-input v-model.trim="formData.name"></el-input>
                </el-form-item>
                <el-form-item label="助记码：" prop="mnemonicCode">
                    <el-input v-model.trim="formData.mnemonicCode"></el-input>
                </el-form-item>
                <el-form-item label="性别：" prop="sex">
                    <el-select v-model="formData.sex" placeholder="选择性别" style="width: 100%;">
                        <el-option :label="'女'" value="0"></el-option>
                        <el-option :label="'男'" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="身份证：" prop="idNumber">
                    <el-input v-model.trim="formData.idNumber"></el-input>                    
                </el-form-item>
                <el-form-item label="出生日期：" prop="birthday">
                    <el-date-picker v-model="formData.birthday" type="date" placeholder="选择出生日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="手机：" prop="phone">
                    <el-input v-model.trim="formData.phone"></el-input>
                </el-form-item>
                <el-form-item label="座机：" prop="telephone">
                    <el-input v-model.trim="formData.telephone"></el-input>
                </el-form-item>
                <el-form-item label="微信：" prop="wechatNumber">
                    <el-input v-model.trim="formData.wechatNumber"></el-input>
                </el-form-item>
                <el-form-item label="QQ：" prop="qqNumber">
                    <el-input v-model.trim="formData.qqNumber"></el-input>
                </el-form-item>
                <el-form-item label="微博：" prop="microblogNumber">
                    <el-input v-model.trim="formData.microblogNumber"></el-input>
                </el-form-item>
                <el-form-item label="文化程度：" prop="education">
                    <el-select v-model="formData.education" placeholder="选择文化程度" style="width: 100%;">
                        <el-option v-for="item in educationList" :key="item['id']" :label="item['detailedName']" :value="item['id']"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门：" prop="department">
                    <el-input v-model="lastDepart" readonly placeholder="选择部门" @click.native="showAddDepartment"></el-input>
                    <el-input v-model="formData.department" style="display: none;"></el-input>
                </el-form-item>
                <el-form-item label="职务：" prop="position">
                    <el-select v-model="formData.position" placeholder="选择职务" style="width: 100%;">
                        <el-option v-for="item in positionList" :key="item['id']" :label="item['detailedName']" :value="String(item['id'])"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="开户银行：" prop="bank">
                    <el-input v-model.trim="formData.bank"></el-input>
                </el-form-item>
                <el-form-item label="开户网点：" prop="bankBranches">
                    <el-input v-model.trim="formData.bankBranches"></el-input>
                </el-form-item>
                <el-form-item label="银行账号：" prop="bankAccount">
                    <el-input v-model.trim="formData.bankAccount"></el-input>
                </el-form-item>
                <el-form-item label="入职时间：" prop="hiredate">
                    <el-date-picker v-model="formData.hiredate" type="date" placeholder="选择入职时间" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="离职时间：" prop="termdate">
                    <el-date-picker v-model="formData.termdate" type="date" placeholder="选择离职时间" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="地址：" prop="address">
                    <el-input v-model.trim="formData.address"></el-input>
                </el-form-item>
                <el-form-item label="职员类别：" prop="type">
                    <el-select v-model="formData.type" placeholder="选择职员类别" style="width: 100%;">
                        <el-option v-for="item in employeeTypeList" :key="item['id']" :label="item['detailedName']" :value="item['id']"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注：" prop="remark">
                    <el-input type="textarea" autosize v-model.trim="formData.remark"></el-input>
                </el-form-item>
                <el-form-item label="连续增加：" v-if="!rowId" style="margin-bottom: 10px !important">
                    <el-checkbox v-model="continueAdd"></el-checkbox>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" @click="save('formRef')">保存</el-button>
                    <el-button type="danger" size="small" @click="close">关闭</el-button>
                </el-form-item>
            </el-form>
        </el-scrollbar>
	</div>
</template>
<script>
export default {
	data() {
		let checkIsPhone = (rule, value, callback) => {
			if(!value){
                callback(new Error('手机不能为空'))
            }else{
                if(!this.$util.checkPhone(value)){ 
                    callback(new Error('手机号码有误'))
                }else{
                    this.$http.post('employee/findUsernameByPhone?phone=' + value).then(res => {
                        if(res.data.code == 20001){
                            callback();
                            this.formData['userName'] = res.data.data;
                        }else{
                        	if(!this.rowId) {			//修改不做校验
                        		this.formData['userName'] = "";
                            	callback(new Error(res.data.msg));
                        	}
                        }
                        callback();
                    })
                }
            }
		}
		return {
			formData: {
				hiredate: this.defaultShowDate(),
				department: ''
			},
			formRules: {
				name: [{required: true, message: '名称不能为空', triggle: 'blur'}],
				sex: [{required: true, message: '性别不能为空', triggle: 'change'}],
				phone: [{required: true, validator: checkIsPhone, triggle: 'blur'}],
				department: [{required: true, message: '部门不能为空', triggle: 'blur'}],
				position: [{required: true, message: '职务不能为空', triggle: 'change'}],
				bank: [{required: true, message: '开户银行不能为空', triggle: 'blur'}],
				bankBranches: [{required: true, message: '开户网点不能为空', triggle: 'blur'}],
				bankAccount: [{required: true, message: '银行账号不能为空', triggle: 'blur'}]
			},
			lastDepart: '',
			departmentName: this.$store.state.empStore.lastDepartmentName,			//部门名称
			parentId: this.$store.state.empStore.parentId,				//部门id
			continueAdd: false,			//是否连续新增
			educationList: [],			//文化程度
			positionList: [],			//职务列表
			employeeTypeList: [],		//职员类型列表
		}
	},
	computed: {
		systemId() {
			return this.$store.state.systemId;
		},
		expandNodeId() {
			return this.$store.state.empStore.expandNodeId;
		},
		rowId() {
			return this.$store.state.empStore.rowId;
		}
	},
	watch: {
        parentId(newVal) {			//监听部门id变化，赋值给表单部门数据
            this.formData['department'] = newVal[0].toString();
        },
        departmentName(newVal) {
        	this.lastDepart = newVal[0];
        },
        'formData.hiredate'(newVal) {			//如果入职时间大于离职时间，清空离职时间数据，重新输入
        	if(new Date(newVal).getTime() > new Date(this.formData['termdate']).getTime()) {
        		this.formData['termdate'] = '';
        	}
        }
    },
	methods: {
		getUpdateData() {		//获取修改数据
			this.$http.get('employee/findSingleEmployee?id=' + this.rowId).then(res => {
				if(res.data.code == 20001) {
					if(res.data.data) {
                        res.data.data['sex'] = String(res.data.data['sex']);
						res.data.data['department'] = res.data.data['department'].toString();
						res.data.data['position'] = res.data.data['position'].toString();
						this.lastDepart = res.data.data['deptName'];
						this.formData = res.data.data;
					}
				}
			});
		},
		getEducationList() {			//获取文化程度列表
			let categoryName = encodeURI('文化程度');
			this.$http.get('employee/InformationByName?categoryName=' + categoryName + '&systemId=' + this.systemId).then(res => {
				if(res.data.code == 20001) {
					if(res.data.data && res.data.data.length > 0) {
						this.educationList = res.data.data;
					}
				}
			});
		},
		getPositionList() {				//获取职务列表
			let categoryName = encodeURI('职务');
            this.$http.get('employee/InformationByName?categoryName='+ categoryName + '&systemId=0').then(res => {
                if(res.data.code == 20001) {
                	if(res.data.data && res.data.data.length > 0) {
						this.positionList = res.data.data;
					}                      
                }
            });
		},
		getEmployeeTypeList() {			//职员类型列表
			let categoryName = encodeURI('职员类别');
            this.$http.get('employee/InformationByName?categoryName='+ categoryName + '&systemId=' + this.systemId).then(res => {
                if(res.data.code == 20001) {
                	if(res.data.data && res.data.data.length > 0) {
						this.employeeTypeList = res.data.data;
					}                      
                }
            });
		},
		defaultShowDate() {
			let date = new Date(),
				year = date.getFullYear(),
				month = date.getMonth() + 1,
				day = date.getDate();
			if(month < 10) month = '0' + month;
			if(day < 10) day = '0' + day;
			return year + '-' + month + '-' + day;
		},
		showAddDepartment() {			//部门新增窗口
            this.$util.openLayerIframe({title: '职员-部门选择', width: '400px', height: '350px', url: this.$domain + '/#/basicData/employee/EmployeeAddDepartment'});
		},
		save(formName) {
			let data = {
				userName: this.formData['userName'],
                name: this.formData['name'],
                mnemonicCode: this.formData['mnemonicCode'],
                sex: this.formData['sex'],
                idNumber: this.formData['idNumber'],
                birthday: this.formData['birthday'],
                phone: this.formData['phone'],
                telephone: this.formData['telephone'],
                wechatNumber: this.formData['wechatNumber'],
                qqNumber: this.formData['qqNumber'],
                microblogNumber: this.formData['microblogNumber'],
                education: this.formData['education'],
                department : this.formData['department'],
                position: this.formData['position'],
                bank: this.formData['bank'],
                bankBranches:this.formData['bankBranches'],
                bankAccount:this.formData['bankAccount'],
                hiredate: this.formData['hiredate'],
                termdate: this.formData['termdate'],
                address: this.formData['address'],
                type: this.formData['type'],
                remark: this.formData['remark'],
                systemId:this.systemId
			}
			if(!this.formData['id']) {				//新增
				this.$http({
                    method: "post",
                    url: "employee/insertEmployee",
                    params: data
                }).then(res => {
                	if(res.data.code == 20001) {
                		this.$message({message: '新增成功', type: 'success', duration: 1500});
                		this.$store.commit('empStore/updateExpandNodeId', data['department']);			//更新刷新点
                		setTimeout(() => {
                			this.continueAdd ? this.$refs[formName].resetFields() : this.close();
                			this.$store.dispatch('empStore/getTreeData');
                			this.$store.dispatch('empStore/getSearch');         //同时更新下关键字搜索数据
                		}, 1000);
                	} else {
                		this.$message({message: res.data.msg || '新增失败', type: 'error', duration: 1500});
                	}
                });
			} else {
                data['id'] = this.formData['id'];			//加上修改数据的id
				//修改
				this.$http({
                    method: "post",
                    url: "employee/updateEmployee",
                    params: data,
                    dataType: 'json'
                }).then(res => {
                    if(res.data.code == 20001) {
                    	this.$store.commit('empStore/updateRowId');			//清空state中的rowId
                        this.$message({message: '数据修改成功', type: 'success', duration: 1500});
                        let expandNodeId = this.$store.state.empStore.expandNodeId;
                        setTimeout(() => {
                            this.$store.dispatch('empStore/getEmployeeDataByDepartmentId', expandNodeId);			//刷新数据
                            this.$store.dispatch('empStore/getSearch');
                            this.close();
                        }, 1000);                       
                    }else{
                        this.$message({message: res.data.msg,type:'error'});
                    }
                })
			}
		},
		close() {           //关闭新增弹窗
            let index = parent.layer.getFrameIndex(window.name);    //先得到当前iframe层的索引
            parent.layer.close(index);
        },
        enterKey(lastRef, nextRef) {		//回车键换行
            if(lastRef.target.value) {
                this.$refs[nextRef].focus();
            }
        }
	},
	created() {
		if(this.rowId) this.getUpdateData();
		this.getEducationList();
		this.getPositionList();
		this.getEmployeeTypeList();
	}
}	
</script>
<style>
	.employeeAddForm .el-input--prefix .el-input__inner {padding-left: 15px !important;}
</style>